// store/modules/auth.js
import {login} from '@/api/api.js';
import axios from "axios";

export default {
    namespaced: true,
    state: {
        token: localStorage.getItem('token') || '',
        userInfo: null,
        orders: [],
        loginDialogVisible: false ,// 添加这个状态
        registerDialogVisible: false, // 添加控制注册对话框的可见性状态
    },

    getters: {
        isLoggedIn: state => {
            const tokenValue = state.token && state.token.trim();
            return tokenValue !== '';
        },
        getToken: state => state.token,
        getUserInfo: state => state.userInfo,
        getOrders: state => state.orders,
        isLoginDialogVisible: state => state.loginDialogVisible, // 新增getter
        isRegisterDialogVisible: state => state.registerDialogVisible, // 新增getter
    },

    mutations: {

        SET_TOKEN(state, token) {
            state.token = token;
        },
        CLEAR_TOKEN(state) {
            state.token = '';
            state.userInfo = null;
            state.orders = [];
        },
        SET_USER_INFO(state, userInfo) {
            state.userInfo = userInfo;
        },
        SET_ORDERS(state, orders) {
            state.orders = orders;
        },
        TOGGLE_LOGIN_DIALOG(state, isVisible) {
            console.log('TOGGLE_LOGIN_DIALOG',state.loginDialogVisible);
            state.loginDialogVisible = isVisible;
        },
        TOGGLE_REGISTER_DIALOG(state, isVisible) {
            console.log('TOGGLE_REGISTER_DIALOG',state.registerDialogVisible);
            state.registerDialogVisible = isVisible;
            console.log('TOGGLE_REGISTER_DIALOG',state.registerDialogVisible);
        },
        UPDATE_USER_INFO(state, updatedUser) {
            state.userInfo = { ...state.userInfo, ...updatedUser };
        },
    },

  actions: {
    async login({ commit }, { userID, password }) {
      try {
        const response = await login(userID, password);
        if (response.statusCode === 200) {
          const userData = response;
          commit('SET_TOKEN', userData.data);
          commit('SET_USER_INFO', {
            userID: userData.data.userID,
            username: userData.data.username,
            phoneNumber: userData.data.phoneNumber,
            userAddress: userData.data.userAddress
          });
        } else {
          const errorMessage = response && response.data ? response.data.message : '登录请求失败';
          throw new Error(errorMessage);
        }
      } catch (error) {
        console.error('auth.js登录失败:', error.message);
        throw error;
      }
    },
    async fetchUser({ commit, getters }) {
      try {
        const token = getters.getToken;
        const response = await axios.get('/api/user/info', {
          headers: {
            'token': token
          }
        });
        if (response.data.statusCode === 200) {
          commit('SET_USER_INFO', response.data.data);
        } else {
          console.error('Error fetching user:', response.data.message);
        }
      } catch (error) {
        console.error('Error fetching user:', error);
      }
    },
    async fetchOrders({ commit, getters }) {
      try {
        const token = getters.getToken;
        const response = await axios.get('/api/user/orders', {
          headers: {
            'token': token
          }
        });
        if (response.data.statusCode === 200) {
          commit('SET_ORDERS', response.data.data);
        } else {
          console.error('Error fetching orders:', response.data.message);
        }
      } catch (error) {
        console.error('Error fetching orders:', error);
      }
    },
    async updateUser({ commit, getters }, updatedUser) {
      try {
          const token = getters.getToken;

          const response = await axios.put('/api/user/update', updatedUser, {
              headers: { 'token': token }
          });
          if (response.data.statusCode === 200) {
              commit('UPDATE_USER_INFO', updatedUser);
          } else {
              console.error('Error updating user:', response.data.message);
          }
      } catch (error) {
          console.error('Error updating user:', error);
      }
    },
    logout({ commit }) {
      commit('CLEAR_TOKEN');
    }
  }
};
